package com.why.usercenter.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.why.commonresults.Result;
import com.why.commonresults.UcenterMemberOrder;
import com.why.usercenter.bean.UcenterMember;
import com.why.usercenter.bean.vo.LoginVo;
import com.why.usercenter.bean.vo.RegisterVo;
import com.why.usercenter.service.UcenterMemberService;
import com.why.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author why
 * @since 2021-02-15
 */
@RestController
@RequestMapping("/api/ucenter")
@CrossOrigin
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService service;


    /**
     * @param member
     * @return
     * @ RequestBody要使用post请求，不然错误（老师的错误）
     */

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo member) {
        //这个方法返回一个token值
        String token = service.loginUser(member);
        return Result.ok().data("token", token);
    }


    @PostMapping("/register")
    public Result register(@RequestBody RegisterVo register) {

        String token = service.registerUser(register);
        return Result.ok();
    }


    @GetMapping("/getMemberInfo")
    public Result getMemberInfoByToken(HttpServletRequest request) {
        //调用jwt的token转换工具，根据token获取到用户的id再根据用户的id获取用户信息
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //调用数据库获取用户的信息
        UcenterMember member = service.getById(memberId);
        return Result.ok().data("userInfo", member);
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param id
     * @return
     */

    @GetMapping("/getInfoById/{id}")
    public UcenterMemberOrder getInfoById(@PathVariable String id) {
        UcenterMember member = service.getById(id);
        UcenterMemberOrder memberOrder = new UcenterMemberOrder();
        BeanUtils.copyProperties(member, memberOrder);
        return memberOrder;
    }


    @GetMapping(value = "/countregister/{day}")
    public Result registerCount(
            @PathVariable String day){
        Integer count = service.countRegisterByDay(day);
        return Result.ok().data("countRegister", count);
    }

}

